<template>
    <div class="h-full overflow-y-auto up-pull-load" @scroll="scroll" ref="upPullLoadRef">
        <slot />
    </div>
    <Toast ref="toastRef" />
</template>
    
<script setup lang='ts'>
import { useDebounceFn } from '@vueuse/core';
const upPullLoadRef = ref<HTMLElement>();
const $props = withDefaults(
    defineProps<{
        distance?: number
    }>(),
    {
        distance: 200
    }
)

const toastRef = ref();
const loading = ref(false);
const $emits = defineEmits<{
    (event: 'trigger', res: any): void;
    (event: 'scroll', e: Event): void
}>()

const scrollHandler = (e: Event) => {
    $emits('scroll', e)
    if (loading.value) {
        return;
    }
    const el = e.target as HTMLElement;
    if ((el.scrollHeight - el.scrollTop - el.offsetHeight) < $props.distance) {
        loading.value = true;
        toastRef.value.loading({ duration: 0 });
        $emits('trigger', {
            done() {
                loading.value = false;
                toastRef.value.hide();
            }
        })
    }
}
const scroll = useDebounceFn(scrollHandler, 100, {
    maxWait: 100
})

defineExpose({
    scrollTo(param: ScrollToOptions) {
        upPullLoadRef.value?.scrollTo(param)
    }
})
</script>
    
<style></style>